package com.zh.common.datasource;

/**
 * Title :
 * Description : @类注释说明写在此处@
 * Create on : 2018年07月05日
 * Copyright (C) zh
 *
 * @author department:研发部
 * username:zh-pc
 * @version 修改历史:
 * 修改人 修改日期 修改描述
 * -------------------------------------------<
 */
public class RoutingDataSourceHolder {

    public static final String MASTER_DATASOURCE_NAME = "MASTER_DATASOURCE";

    public static final String SLAVE_DATASOURCE_NAME_PREFIX = "SLAVE_DATASOURCE_";


    public static int SLAVE_DATASOURCE_COUNT = 0;

    private static volatile int slaveDataSourceIndex = 0;

    private RoutingDataSourceHolder() {
    }

    private static final ThreadLocal<String> holder = new ThreadLocal<String>();


    public static void putMasterDataSource() {
        holder.set(MASTER_DATASOURCE_NAME);
    }

    public static void putSlaveDataSource() {
        holder.set(SLAVE_DATASOURCE_NAME_PREFIX + roundRobin());
    }

    private synchronized static int roundRobin() {
        if (slaveDataSourceIndex == SLAVE_DATASOURCE_COUNT) {
            slaveDataSourceIndex = 0;
        }
        return slaveDataSourceIndex++;
    }

    public static String getDataSource() {
        return holder.get();
    }

    public static void clearDataSource() {
        holder.remove();
    }

}
